<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/13
 * Time: 9:48
 */
namespace common\models;

use Yii;
use yii\base\model;

/**
 * 上传文件必须配置两个参数
 *
 * 1. 在 `/common/config/bootstrap.php` 文件中,配置`@uploadPath`的值,例如:`dirname(dirname(__DIR__)) . '/frontend/web/uploads'`
 *
 * 2. 在 `/backend/config/params.php` 文件中,配置`assetDomain`的值,例如:`http://localhost/yii2/advanced/frontend/web/uploads`
 *
 * Class UploadForm
 * @package common\models
 */
class UploadForm extends model
{
    public $imageFile;
    public $excelFile;

    public function rules()
    {
        return [
            //数据验证
            [['imageFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png,jpg,jpeg,png'],
            [['excelFile'], 'file', 'skipOnEmpty' => true, 'checkExtensionByMimeType' => false, 'extensions' => 'xls,xlsx'],
        ];
    }

    public function upload()
    {
        if ($this->validate()) {
            $path = Yii::getAlias('@uploadPath') . '/images/' . date("Ymd");
            if (!is_dir($path) || !is_writable($path)) {
                \yii\helpers\FileHelper::createDirectory($path, 0777, true);
            }
            $filePath = $path . '/' . md5(uniqid() . mt_rand(10000, 99999999)) . '.' . $this->imageFile->extension;
            if ($this->imageFile->saveAs($filePath)) {

                $imageUrl = $this->parseUrl($filePath);
                return $imageUrl;
            }
        }
        return false;
    }

    public function uploadExcel()
    {
        if ($this->validate() && $this->checkExcelFileMime()) {
            $path = Yii::getAlias('@uploadPath') . '/excels/' . date("Ymd");
            if (!is_dir($path) || !is_writable($path)) {
                \yii\helpers\FileHelper::createDirectory($path, 0777, true);
            }
            $filePath = $path . '/' . md5(uniqid() . mt_rand(10000, 99999999)) . '.' . $this->excelFile->extension;
            if ($this->excelFile->saveAs($filePath)) {

                $excelUrl = $this->parseUrl($filePath);
                return $excelUrl;
            }
        }
        return false;
    }

    /**
     * 校验Excel mime类型
     * @return bool
     */
    public function checkExcelFileMime()
    {
        $excel_mime_hash = [
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ];
        if (in_array($this->excelFile->type, $excel_mime_hash, true)) {
            return true;
        }
        return false;
    }

    /**
     * 这里在upload中定义了上传目录根目录别名，以及图片域名
     * 将/var/www/html/advanced/frontend/web/uploads/20160626/file.png 转化为 http://statics.gushanxia.com/uploads/20160626/file.png
     * format:http://domain/path/file.extension
     * @param $filePath
     * @return string
     */
    private function parseUrl($filePath)
    {
        if (strpos($filePath, Yii::getAlias('@uploadPath')) !== false) {
            return str_replace(Yii::getAlias('@uploadPath'), '', $filePath);
        } else {
            return $filePath;
        }
    }
}